package com.fsy.its.netty.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class DtuDecoderBeanRegister implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private DtuDecoderFactory dtuDecoderFactory;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 根容器为Spring容器
        if(event.getApplicationContext().getParent()==null){
            Map<String,Object> beans = event.getApplicationContext().getBeansWithAnnotation(DtuDecoder.class);
            for(Object bean : beans.values()){
                DtuDecoder annotation = AnnotationUtils.findAnnotation(bean.getClass(), DtuDecoder.class);
                log.info("Register a decoder: {} ", bean.getClass().getName());
                String[] models = annotation.model();
                for( String model : models ) {
                    try {
                        dtuDecoderFactory.addDecoderInstance(annotation.brand(), model, bean);
                    }
                    catch (Exception e) {
                        log.error("Register decoder failed: ", e);
                    }
                }
            }
        }
    }
}
